<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="模板号" style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找模板
      </el-button>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="编号" prop="id" sortable="custom" align="center" width="180" />
        <el-table-column label="项目名称" prop="name" align="center" min-width="200px" />
        <el-table-column label="描述" prop="description" align="center" />
        <el-table-column label="状态" prop="stateName" align="center" />
        <el-table-column label="修改人图片" width="80px" align="center">
          <template slot-scope="{row}">
            <img :src="'http://'+row.updateUserImg" width="60px" height="60px">
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center">
          <template slot-scope="{row}">
            <span>{{ row.typeName || 'null' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="createTime" align="center" />
        <el-table-column label="修改时间" prop="updateTime" align="center" />

        <el-table-column label="操作" align="center" min-width="150px" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleCheck(row)">
              查看
            </el-button>
            <el-button type="success" size="mini" @click="handleRestart(row)">
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />
    </div>

    <!-- 查看模板详情 -->
    <div class="dialog-active">
      <el-dialog title="模板详情" :visible.sync="dialogFormVisible">
        <el-form :model="carModel" style="max-height:600px;overflow-y:auto;">
          <el-form-item label="模板名" prop="name">
            <span>{{ carModel.name }}</span>
          </el-form-item>
          <el-form-item label="id" prop="id">
            <span>{{ carModel.id }}</span>
          </el-form-item>
          <el-form-item label="备注：" prop="description">
            <span>{{ carModel.description }}</span>
          </el-form-item>
          <el-form-item label="作者：" prop="createUserName">
            <span>{{ carModel.createUserName }}</span>
          </el-form-item>
          <el-form-item label="状态：" prop="stateName">
            <span>{{ carModel.stateName || 'null' }}</span>
          </el-form-item>
          <el-form-item label="类型：" prop="typeName">
            <span>{{ carModel.typeName || 'null' }}</span>
          </el-form-item>

          <el-form-item label="表单项：" prop="tableOptions"><br>
            <el-form-item style="text-indent:4em" label="类型：">
              <span>{{ carModel.tableOptions.length>0?carModel.tableOptions[0].valueTypeName:'null' }}</span>
            </el-form-item>
            <el-form-item style="text-indent:4em" label="名称：">
              <span
                v-for="item of carModel.tableOptions"
                :key="item.id"
              >
                {{ item.name }}
              </span>
            </el-form-item>
          </el-form-item>

          <el-form-item label="检查项：" prop="options">
            <el-table
              :data="carModel.options"
              style="width: 100%"
            >
              <el-table-column
                prop="group"
                label="组名"
              />
              <el-table-column
                prop="name"
                label="名称"
              />
              <el-table-column
                prop="remarks"
                label="备注"
              />
              <el-table-column
                prop="typeName"
                label="类型"
              />
              <el-table-column
                prop="stateName"
                label="状态"
              />
            </el-table>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            关闭
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { queryTemp, changeTempState, getDetail } from '@/api/template'
import waves from '@/directive/waves' // waves directive水波纹特效？
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 基于el分页的二次封装

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  // 定义过滤器   调用只需要  数据  | 过滤器名
  filters: {
    // 状态过滤器
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }

  },
  data() {
    return {
      dialogFormVisible: false,
      // 搜索框请求数据及分页数据
      listQuery: {
        page: 1,
        pageSize: 10,
        type: '',
        name: '',
        state: 3
      },
      tableKey: 0,
      listLoading: true,
      total: 0,
      list: [],

      carModel: {
        id: '',
        name: '',
        description: '',
        state: '',
        type: 4,
        createUser: '',
        updateUser: '',
        createUserImg: '',
        updateUserImg: '',
        createTime: '',
        updateTime: '',
        stateName: '',
        typeName: '',
        createUserName: '',
        updateUserName: '',
        tableOptions: [{
          id: '',
          name: '',
          type: 10,
          tupeName: '',
          state: 1,
          stateName: '',
          valueType: 1,
          valueTypeName: ''
        }],
        options: [{
          id: '',
          group: '',
          name: '',
          type: 1,
          typeName: '',
          remarks: '',
          state: '',
          stateName: '',
          valueType: 1,
          optionValuePoList: ['']
        }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      queryTemp(this.listQuery).then(response => {
        if (response.resultCode === 200) {
          this.list = response.data.list
          this.total = response.data.count
        }
      })
      this.listLoading = false
    },

    // 查询模板
    handleFilter() {
      this.getList()
    },

    // 查看模板信息按钮
    handleCheck(row) {
      getDetail(row.id, 1).then(response => {
        if (response.resultCode === 200) {
          this.carModel = Object.assign(response.data)
          this.dialogFormVisible = true
        }
      })
    },

    handleRestart(row) {
      const data = {
        modelId: row.id,
        state: 2
      }
      changeTempState(data).then(res => {
        if (res.resultCode === 200) {
          this.$notify({
            title: '提示',
            message: '启用成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      })
    }

    // // 似乎是用来改变状态的，控制状态是draft还是publish（草稿或发布）
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: '操作Success',
    //     type: 'success'
    //   })
    //   row.status = status
    // },

    // // 改变排序的 一开始就绑定在成员列表里了,调用下面的sortByID
    // sortChange(data) {
    //   const { prop, order } = data
    //   if (prop === 'id') {
    //     this.sortByID(order)
    //   }
    // },

    // // 按id排序，递增或递减
    // sortByID(order) {
    //   if (order === 'ascending') {
    //     this.listQuery.sort = '+id'
    //   } else {
    //     this.listQuery.sort = '-id'
    //   }
    //   this.handleFilter()
    // },

    // // 重置temp缓存数据 在每次点击新增和修改时调用，避免数据出错
    // resetTemp() {
    //   this.temp = {
    //     id: '',
    //     name: '',
    //     nickName: '',
    //     account: '',
    //     img: '',
    //     role: '',
    //     sex: '',
    //     password: '',
    //     state: '',
    //     email: '',
    //     phone: ''
    //   }
    // },

    // // 点击新增按钮触发的方法  展示新增界面
    // // handleCreate() {
    // // 重置temp
    // //   this.resetTemp()
    // //   this.dialogStatus = 'create'
    // //   this.dialogFormVisible = true
    // //   this.$nextTick(() => {
    // //     this.$refs['dataForm'].clearValidate()
    // //   })
    // // },

    // // 增删改函数
    // handleUpdate(row) {
    //   this.temp = Object.assign({}, row) // copy obj
    //   // this.temp.timestamp = new Date(this.temp.timestamp)
    //   this.dialogStatus = 'update'
    //   this.dialogFormVisible = true
    //   this.$nextTick(() => {
    //     this.$refs['dataForm'].clearValidate()
    //   })
    // },

    // // 更新修改数据
    // updateData() {
    //   console.log('确认', this.temp)
    //   this.$refs['dataForm'].validate((valid) => {
    //     if (valid) {
    //       // console.log('valid')
    //       // Number(this.temp.sex)
    //       // Number(this.temp.state)
    //       // const tempData = Object.assign({}, this.temp)
    //       const tempData = {
    //         id: this.temp.id,
    //         name: this.temp.name
    //       }

    //       console.log(tempData)
    //       // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
    //       updateArticle(tempData).then(() => {
    //         const index = this.list.findIndex(v => v.id === this.temp.id)
    //         this.list.splice(index, 1, this.temp)// 从index的位置开始更新1个元素
    //         this.dialogFormVisible = false
    //         this.$notify({
    //           title: 'Success',
    //           message: '修改成功',
    //           type: 'success',
    //           duration: 2000
    //         })
    //       })
    //     }
    //   })
    // },

    // // 绑定恢复事件，恢复表格当前这行
    // handleRecovery(row, index) {
    //   recoveryArticle(row.id).then(() => {
    //     if (res.resultCode == 200) {
    //       this.$notify({
    //         title: '提示',
    //         message: '恢复成功！',
    //         type: 'success',
    //         duration: 2000
    //       })
    //     }
    //     this.list.splice(index, 1)
    //     // resetTemp()
    //   }).catch(err => {
    //     console.log(err)
    //   })
    //   this.list.splice(index, 1)
    // },

    // // 下载？导出成excel？
    // handleDownload() {
    //   this.downloadLoading = true
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const data = this.formatJson(filterVal)
    //     excel.export_json_to_excel({
    //       header: tHeader,
    //       data,
    //       filename: 'table-list'
    //     })
    //     this.downloadLoading = false
    //   })
    // },

    // // 时间控件
    // formatJson(filterVal) {
    //   return this.list.map(v => filterVal.map(j => {
    //     if (j === 'timestamp') {
    //       return parseTime(v[j])
    //     } else {
    //       return v[j]
    //     }
    //   }))
    // },

    // getSortClass: function(key) {
    //   const sort = this.listQuery.sort
    //   return sort === `+${key}` ? 'ascending' : 'descending'
    // }
  }
}
</script>

<style lang="scss">
  .footer {
    background-color: #ecf5ff;
    color: black;
    margin: 0;
    position:absolute; /* 必要 */
    bottom:0; /* 必要 */
    width: 100%;
  }
</style>
